import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class Utils {
    public static int INT_LEN = 4;
    public static int FLOAT_LEN = 4;

    public static byte[] int2bytes(int val) {
        byte[] ans = new byte[4];
        writeInt(val, ans, 0);
        return ans;
    }

    public static int bytes2int(byte[] val) {
        return readInt(val, 0);
    }

    public static int readInt(byte[] val, int offset) {
        int ans = 0;
        ans |= val[offset] & 0xFF;
        ans |= ((int)val[offset + 1] & 0xFF) << 8;
        ans |= ((int)val[offset + 2] & 0xFF) << 16;
        ans |= ((int)val[offset + 3] & 0xFF) << 24;
        return ans;
    }

    public static void writeInt(int val, byte[] buf, int offset) {
        buf[offset] = (byte) (val & 0xFF);
        buf[offset + 1] = (byte) ((val >> 8) & 0xFF);
        buf[offset + 2] = (byte) ((val >> 16) & 0xFF);
        buf[offset + 3] = (byte) ((val >> 24) & 0xFF);
    }

    public static float readFloat(byte[] val, int offset) {
        int intBytes = readInt(val, offset);
        return Float.intBitsToFloat(intBytes);
    }

    public static void writeFloat(float val, byte[] buf, int offset) {
        int intBytes = Float.floatToIntBits(val);
        writeInt(intBytes, buf, offset);
    }

    public static String readString(byte[] val, int offset, int len) {
        for (int i = 0; i < len; i++) {
            if(val[offset + i] == 0) {
                len = i;
                break;
            }
        }
        return new String(val,offset,len, StandardCharsets.UTF_8);
    }

    public static void writeString(String val, byte[] buf, int offset, int len) {
        byte[] data = val.getBytes(StandardCharsets.UTF_8);
        len = Math.min(data.length, len);
        for (int i = 0; i < len; i++) {
            buf[offset + i] = data[i];
        }
        if (len > data.length) {
            buf[offset + len] = 0;
        }
    }

    public static void main(String[] args) {
//        int test = 0x1234;
//        System.out.println("test = " + Integer.toHexString(test));
//        System.out.println("bytes: " + Arrays.toString(int2bytes(test)));

        //中文test
        byte[] buf = {-28, -72, -83, -26, -106, -121, 116, 101, 115, 116, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
        System.out.println("(" + readString(buf, 0, 15) + ")");

        byte[] buf2 = new byte[256];
        writeString("中文", buf2, 0, 10);
        System.out.println("bytes: " + Arrays.toString(buf2));
    }
}
